package com.dp.selenium.grid.demo.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.dp.selenium.grid.demo.common.RstMsg;

public class Executor {

	private List<DoTest> list = new ArrayList<DoTest>();

	public void register(DoTest tester) {
		list.add(tester);
	}

	public void reset() {
		list.clear();
	}

	public RstMsg execute() throws InterruptedException {

		ExecutorService exec = Executors.newCachedThreadPool();
		ArrayList<Future<RstMsg>> results = new ArrayList<Future<RstMsg>>();

		for (DoTest tester : list) {
			results.add(exec.submit(tester));
		}

		while (!isAllDown(results)) {
			Thread.sleep(2 * 1000);
		}
		try {
			printRst(results);
		} catch (ExecutionException e) {
			return RstMsg.getFaild(e.getMessage());

		}
		return RstMsg.getSucess();
	}

	private List<RstMsg> printRst(ArrayList<Future<RstMsg>> results) throws InterruptedException, ExecutionException {
		List<RstMsg> rstList=new ArrayList<RstMsg>();
		for (Future<RstMsg> fs : results) {
			System.out.println(fs.get().getMsg());
			rstList.add(fs.get());
		}
		return rstList;
	}

	private boolean isAllDown(ArrayList<Future<RstMsg>> results) {
		for (Future<RstMsg> fs : results) {
			if (!fs.isDone()) {
				return false;
			}
		}
		return true;
	}
}
